package com.crm.service.impl;

import com.crm.mapper.DeptMapper;
import com.crm.pojo.common.ErrorMessage;
import com.crm.pojo.common.PageResult;
import com.crm.pojo.common.UserContext;
import com.crm.pojo.domain.Dept;
import com.crm.pojo.dto.DeptDto;
import com.crm.pojo.vo.DeptVo;
import com.crm.pojo.vo.TreeVo;
import com.crm.service.DeptService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    //部门列表查询
    @Override
    public List<DeptVo> list(DeptDto deptDto) {
        //用pageHelper 进行分页
        //1. 设置分页参数
        PageHelper.startPage(deptDto.getPageNum(),deptDto.getPageSize());
        //2.查询数据
        return deptMapper.list(deptDto);
    }
    //部门新增
    @Override
    public int add(DeptDto deptDto) throws Exception {
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptDto,dept);
        //补全祖先路径和上级部门名字
        //dept.setAncestors(findAncestor(deptDto.getParentId()));
        dept = ancestor(dept);
        dept.setCreateBy(UserContext.getCurrentUser().getUserName());
        dept.setUpdateBy(UserContext.getCurrentUser().getUserName());
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        try {
            return deptMapper.add(dept);
        } catch (Exception e) {
            log.info(e.getMessage());
             throw new Exception(ErrorMessage.DEPT_ERROR_MESSAGE_ADD_001);
        }
    }
    //部门查询（id）
    @Override
    public DeptVo getById(Long id) {
        return deptMapper.getById(id);
    }

    @Override
    public void deleteById(Long id) {
        //先判断其有没有子部门,如果有显示不能删除
        List childrens = deptMapper.children(id);
        if (childrens.size() > 0) {
            throw new RuntimeException(ErrorMessage.DEPT_ERROR_MESSAGE_DELETE_001);
        }
        int res = deptMapper.deleteById(id);
        if (res == 0) {
            throw new RuntimeException(ErrorMessage.DEPT_ERROR_MESSAGE_DELETE_002);
        }
    }
    //部门修改
    @Override
    public void update(DeptDto deptDto) {
        DeptVo oldDept = deptMapper.getById(deptDto.getDeptId());
        List childrens = deptMapper.children(deptDto.getDeptId());
        //如果有子部门，即不能停用且不能更换父部门
        if (childrens.size() > 0) {
            if (deptDto.getStatus().equals("1") && oldDept.getStatus().equals("0")) {
                throw new RuntimeException(ErrorMessage.DEPT_ERROR_MESSAGE_UPDATE_001);
            }
            else if (!deptDto.getParentId().equals(oldDept.getParentId())) {
                throw new RuntimeException(ErrorMessage.DEPT_ERROR_MESSAGE_UPDATE_002);
            }
        }
        //更新部门信息
        Dept newDept = new Dept();
        BeanUtils.copyProperties(deptDto,newDept);
        newDept = ancestor(newDept);
        newDept.setUpdateBy(UserContext.getCurrentUser().getUserName());
        newDept.setUpdateTime(LocalDateTime.now());
        try {
            deptMapper.update(newDept);
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new RuntimeException(ErrorMessage.DEPT_ERROR_MESSAGE_UPDATE_003);
        }

    }

    @Override
    public List exclude(Long id) {
        return deptMapper.exclude(id);
    }
    //部门树结构
    @Override
    public List<TreeVo> deptTreeSelect(Long id) {
        List<TreeVo> treeVos = new ArrayList<>();
        List<DeptVo> deptVos = deptMapper.children(id);
        if (deptVos!=null && deptVos.size()>0){
            treeVos = treeDept(id,deptVos);
        }
        return treeVos;
    }
    //递归查找
    private List<TreeVo> treeDept(Long id, List<DeptVo> deptVos) {
        ArrayList<TreeVo> treeVos = new ArrayList<>();
        for (DeptVo deptVo : deptVos) {
            TreeVo treeVo = new TreeVo();
            treeVo.setId(deptVo.getDeptId());
            treeVo.setLabel(deptVo.getDeptName());
            List<DeptVo> childens = deptMapper.children(deptVo.getDeptId());
            if (childens.size()>0){
                treeVo.setChildren(treeDept(deptVo.getDeptId(),childens));
            }
            treeVos.add(treeVo);
        }
        return treeVos;
    }

    //查询祖先路径
    private Dept ancestor(Dept dept) {
        Long parentId = dept.getParentId();
        String path ="";
        if (parentId == 0) {
            path = 0+"";
            dept.setAncestors(path);
            return dept;
        }
        ArrayList<String> list = new ArrayList<>();
        int count = 0;
        while (parentId != 0){
            list.add(parentId+"");
            DeptVo deptVo = deptMapper.getById(parentId);
            if (count == 0 && deptVo != null ){
                dept.setParentName(deptVo.getDeptName());
                count++;
            }
            parentId = deptVo.getParentId();
        }
        list.add(0+"");
        for (String s : list) {
            path = s+","+path;
        }
        path = path.substring(0,path.length()-1);
        dept.setAncestors(path);
        return dept;
    }
}
